package com.sky.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import com.sky.properties.AliOssProperties;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

public class IMageUploadUtils {

    private final AliOssProperties aliOssProperties;

    public IMageUploadUtils(AliOssProperties aliOssProperties) {
        this.aliOssProperties = aliOssProperties;
    }

    /**
     * 图片上传
     *
     * @param originalFilename 原始文件名
     * @param content          文件内容
     * @return 文件上传路径
     */
    public String upload(String originalFilename, byte[] content) throws ClientException {
        // 设置 OSS Endpoint 和 Bucket 名称
        String endpoint = aliOssProperties.getEndpoint();
        String bucketName = aliOssProperties.getBucketName();
        // 替换为您的 Bucket 区域
        String region = aliOssProperties.getRegion();
        //获取文件名前缀字符串和后缀文件类型
        String prefix = UUID.randomUUID().toString().replace("-", "");
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = prefix + suffix;
        //获取当前日期,当作文件夹
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        //上传的文件名
        String objectName = dir + "/" + fileName;
        // 从系统变量中获取accessKey
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 创建 OSSClient 实例
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)// 设置 OSS Endpoint
                .credentialsProvider(credentialsProvider)// 设置凭证提供者
                .region(region)// 设置区域
                .build();
        // 2. 上传文件
        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
            System.out.println("文件 " + objectName + " 上传成功。");
        } finally {
            ossClient.shutdown();
        }
        // 返回文件访问路径
        return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
    }
}